package com.joint.web.action.manage;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.*;
import com.joint.base.service.activiti.WorkflowService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.manage.Dispatch;
import com.joint.core.entity.manage.Receive;
import com.joint.core.service.DispatchService;
import com.joint.core.service.ReceiveService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;


@ParentPackage("manage")
public class AjaxReceiveAction extends BaseFlowAction {
    @Resource
    private WorkflowService workflowService;
    @Resource
    private ReceiveService receiveService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PostService postService;
    @Resource
    private PowerService powerService;
    @Resource
    private DutyService dutyService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private ReadersService readersService;
    @Resource
    private TaskRecordService taskRecordService;

    /**
     * 收文登记对象(读)
     */
    private Receive receive;

    /**
     * 登录人(读)
     */
    private Users loginUser;
    /**
     * 附件上传Id(读)
     */
    private String fileId;

    /**
     * 收文类别（读）
     */
    private List<Map<String, Object>> typeDict;

    /**
     *  收文类别
     */
    private String typedictId;
    /**
     *  收文标题
     */
    private String title;
    /**
     * 收文编号
     */
    private String receiveNo;
    /**
     * 收文时间
     */
    private String time;

    /**
     * 有效期限
     */
    private String validDate;

    /**
     * 传阅对象
     */
    private String passObjectId;
    /**
     * 附件上传Id
     */
    private String fileIds;
    /**
     * 视图类型
     */
    private String viewtype;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "receive";
    }



    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        if(viewtype !=null && viewtype.equals("2")){
            pager.setOrderBy("modifyDate");
        }
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();

        params = getSearchFilterParams(_search,params,filters);

        /*内嵌视图这里要加上
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(parentId)){
            manageProInfo = manageProInfoService.get(parentId);
            params.put("manageProInfo",manageProInfo);
        }*/
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
      //  LogUtil.info("viewtype:" + viewtype);
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
              //  params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                params.put("invalid", false);
                pager=receiveService.findByPagerAndLimit("com.joint.core.entity.manage.Receive",  new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed}, pager, params);
            }else if(viewtype.equals("2")){
                //已归档
              //  params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                params.put("invalid", false);
                pager=receiveService.findByPagerAndLimit("com.joint.core.entity.manage.Receive", new FlowEnum.ProcessState[]{FlowEnum.ProcessState.Finished}, pager, params);
            }else if(viewtype.equals("3")){
                //已失效
                params.put("invalid", true);
                pager=receiveService.findByPagerAndLimit("com.joint.core.entity.manage.Receive",  null, pager, params);
            }
        }else{
            //所有单子
          //  params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=receiveService.findByPagerAndLimit("com.joint.core.entity.manage.Receive",  new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, pager, null);
        }

        List<Receive>  receiveList;
        if (pager.getTotalCount() > 0){
            receiveList = (List<Receive>) pager.getList();
        }else{
            receiveList= new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Receive receive: receiveList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",receive.getId());
            rMap.put("type",receive.getType() != null?receive.getType().getName():"");
            rMap.put("receiveNo",receive.getReceiveNo());
            rMap.put("title",receive.getTitle());
            rMap.put("time", DataUtil.DateToString(receive.getTime()));
            rMap.put("creater", receive.getCreater() != null ? receive.getCreater().getName() : "");
            rMap.put("createDate", DataUtil.DateToString(receive.getCreateDate(),"yyyy-MM-dd"));
            rMap.put("state",receive.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records", recordsNum);


        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    public String read(){
        loginUser = usersService.getLoginInfo();

        if(StringUtils.isNotEmpty(keyId)) {
            fileId ="";
            receive = receiveService.get(keyId);
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            flowNumStatus = workflowService.getFlowNumStatus(keyId);
            if(receive.getFile() != null && receive.getFile().size()>0){
                for(FileManage f:receive.getFile()){
                    fileId+=f.getId()+",";
                }
            }

        }


        return "read";
    }


    public String input(){
        Company company = usersService.getCompanyByUser();
        List<Dict> receiveType = dictService.listFormDefinedEnable(DictBean.DictEnum.ReceiveType, usersService.getCompanyByUser().getId());
        Map<String,Object> rMap = null;
        typeDict = new ArrayList<Map<String, Object>>();
        if (StringUtils.isNotEmpty(keyId)){
            fileId ="";
            receive = receiveService.get(keyId);
            if(receive.getFile() != null && receive.getFile().size()>0){
                for(FileManage f:receive.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            for(Dict typeObj:receiveType){
                rMap = new HashMap<String, Object>();
                rMap.put("id",typeObj.getId());
                rMap.put("name",typeObj.getName());
                rMap.put("selected","");
                if(receive.getType()!=null && StringUtils.equals(typeObj.getId(), receive.getType().getId())){
                    rMap.put("selected","selected");
                }
                typeDict.add(rMap);
            }
        } else {
            for(Dict typeObj:receiveType){
                rMap = new HashMap<String, Object>();
                rMap.put("id",typeObj.getId());
                rMap.put("name",typeObj.getName());
                rMap.put("selected","");
                typeDict.add(rMap);
            }

        }

        return "input";
    }

    private void setData(){
        if(StringUtils.isNotEmpty(keyId)){
            receive = receiveService.get(keyId);
        }else{
            receive = new Receive();
            receive.setCreater(usersService.getLoginInfo());
        }
        if(StringUtils.isNotEmpty(typedictId)){
            receive.setType(dictService.get(typedictId));
        }
        receive.setTitle(title);
        receive.setReceiveNo(receiveNo);
        if(StringUtils.isNotEmpty(time)){
            receive.setTime(DataUtil.StringToDate(time));
        }
        if(StringUtils.isNotEmpty(validDate)){
            receive.setValidDate(DataUtil.StringToDate(validDate));
        }
        List<Users> usersList = Lists.newArrayList();
        Set<Duty> dutySet = Sets.newHashSet();
        if(StringUtils.isNotEmpty(passObjectId)){
            String[] idArr = passObjectId.split(",");
            for(String id:idArr){
                usersList.add(usersService.get(id.trim()));
                dutySet.addAll(dutyService.getDutys(usersService.get(id.trim())));
            }
        }
        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManageService.get(f.trim()));
            }
        }
        String dutyIds = "";
        for(Duty duty:dutySet){
            dutyIds += duty.getId()+",";
        }
        if(StringUtils.isNotEmpty(dutyIds)){
            dutyIds =  dutyIds.substring(0, dutyIds.length()-1);
        }
        receive.setDutyIds(dutyIds);
        receive.setPassObject(usersList);
        receive.setFile(fileManageList);
        receive.setCompany(usersService.getLoginInfo().getCompany());
    }

    // 保存
    public String save(){
        setData();
        if(StringUtils.isNotEmpty(keyId)){
            receiveService.update(receive);
        } else {
            receiveService.save(receive, "com.joint.core.entity.manage.Receive");
        }
        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }


    // 提交
    public String commit(){
        setData();
        /*
        Company company = usersService.getCompanyByUser();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        ArrayList<String> list = new ArrayList<String>();
        for (String uid: passObjectId.split(",")) {
            list.add(uid.trim());
        }
        var2.put("approvers", list);
        Set<Users> usersSet = Sets.newHashSet();
        Map<String, Object> map = new HashMap<String, Object>();
        List<Users> usersList = receive.getPassObject();
        for(Users users:usersList){
            usersSet.add(users);
        }*/


        if (StringUtils.isNotEmpty(keyId)) {
            receiveService.approve(receive, dutyService.get(curDutyId), comment);
        } else {
            keyId = receiveService.commit(receive, "com.joint.core.entity.manage.Receive", dutyService.get(curDutyId));
        }
       /*
        //先删除读者
        readersService.deleteByKeyIdBussinessKey(keyId);
        //增加归档后读者
        for(Users users:usersSet){
            Readers readers = new Readers();
            readers.setUsers(users);
            readers.setBussinessKey("dispatch");
            readers.setKeyId(keyId);
            readers.setType(2);
            readersService.save(readers);
        }*/
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批
    public String approve(){
        receive = receiveService.get(keyId);
        receiveService.approve(receive, dutyService.get(curDutyId), comment);
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }
    //审批1
    public String approve1(){
        receive = receiveService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                receiveService.approve(receive, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
            Task overtask = workflowService.getCurrentTask(keyId);

            if(overtask==null){
                Receive receive = receiveService.get(keyId);
                receive.setProcessState(FlowEnum.ProcessState.Finished);
                receiveService.update(receive);
                List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(receive.getId());
                for(TaskRecord taskRecord:taskRecords){
                    taskRecord.setType(2);
                    taskRecordService.update(taskRecord);
                }
            }else {
                if (runtimeService.getVariable(overtask.getExecutionId(), "nrOfCompletedInstances") == null) {
                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 2);
                }
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    /**
     * 退回
     * @return
     */
    public String reject() {
        if (StringUtils.isNotEmpty(keyId)) {
            receive = receiveService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("dispatch");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
           // System.out.println("comment:"+comment);
             LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            receiveService.reject(receive, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String back() {
        if (StringUtils.isNotEmpty(keyId)) {
            receive = receiveService.get(keyId);
            receiveService.back(receive, dutyService.get(curDutyId), comment);
        }
        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (StringUtils.isNotEmpty(keyId)) {
            receive = receiveService.get(keyId);
            receiveService.deny(receive, dutyService.get(curDutyId), comment);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }
    /**
     * 否决
     * @return
     */
    public String deny1() {
        if (StringUtils.isNotEmpty(keyId)) {
            receive = receiveService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("dispatch");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:" + key);
            if(StringUtils.isEmpty(comment)){
                comment="";
            }
            receiveService.deny(receive, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }

    /**
     * 失效
     * @return
     */
    public String doInvalid(){
        if(StringUtils.isNotEmpty(keyId)) {
            receive = receiveService.get(keyId);
            receive.setInvalid(true);
            receiveService.update(receive);
        }
        return ajaxHtmlCallback("200", "操作成功！", "操作状态");
    }

    public Receive getReceive() {
        return receive;
    }

    public void setReceive(Receive receive) {
        this.receive = receive;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getFileId() {
        return fileId;
    }

    public void setFileId(String fileId) {
        this.fileId = fileId;
    }

    public List<Map<String, Object>> getTypeDict() {
        return typeDict;
    }

    public void setTypeDict(List<Map<String, Object>> typeDict) {
        this.typeDict = typeDict;
    }

    public String getTypedictId() {
        return typedictId;
    }

    public void setTypedictId(String typedictId) {
        this.typedictId = typedictId;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getReceiveNo() {
        return receiveNo;
    }

    public void setReceiveNo(String receiveNo) {
        this.receiveNo = receiveNo;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getValidDate() {
        return validDate;
    }

    public void setValidDate(String validDate) {
        this.validDate = validDate;
    }

    public String getPassObjectId() {
        return passObjectId;
    }

    public void setPassObjectId(String passObjectId) {
        this.passObjectId = passObjectId;
    }

    public String getFileIds() {
        return fileIds;
    }

    public void setFileIds(String fileIds) {
        this.fileIds = fileIds;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }
}

